package com.budwk.app.sqfwV2.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.budwk.app.sqfw.dto.PeopleTagDTO;
import com.budwk.app.sqfw.dto.PersonnelTagDTO;
import com.budwk.app.sqfw.models.PersonInfo;
import com.budwk.app.sqfw.models.Sqfw_cenSusPaper;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.PersonInfoService;
import com.budwk.app.sqfw.services.SqfwFormSummaryService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.DownDataVo;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwDoc.dto.TemplateCodeUpdateDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownFileTypesResVo;
import com.budwk.app.sqfwV2.dto.weiqingmen.HouseHoldSurveyDTO;
import com.budwk.app.sqfwV2.dto.weiqingmen.InterviewDTO;
import com.budwk.app.sqfwV2.enums.weiqingmen.HouseHoldSurveyEnum;
import com.budwk.app.sqfwV2.service.weiqingmen.HouseHoldSurveyExcelService;
import com.budwk.app.sqfwV2.service.weiqingmen.HouseHoldSurveyPdfService;
import com.budwk.starter.common.openapi.annotation.ApiDefinition;
import com.budwk.starter.common.openapi.annotation.ApiOperation;
import com.budwk.starter.common.openapi.annotation.ApiResponses;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.log.annotation.SLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 东方祥云低代码1.1
 * @since 2024-04-01
 *
 * 威清门消防安全排查 SafetyCheck
 */
@IocBean
@At("/platform/sqfw/weiQingMenHouseHoldSurvey")
@ApiDefinition(tag = "消防信息")
@Slf4j
public class WeiQingMenHouseHoldSurveyController {

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;
    @Inject
    private HouseHoldSurveyPdfService houseHoldSurveyPdfService;
    @Inject
    private HouseHoldSurveyExcelService houseHoldSurveyExcelService;
    @Inject
    private PersonInfoService personInfoService;
    @Inject
    private SqfwFormSummaryService sqfwFormSummaryService;

    @At("/v2/submitData")
    @Ok("json")
    @POST
    @ApiOperation(name = "保存数据并创建pdf")
    @SLog(tag = "保存数据并创建pdf", value = "${args[0]}")
    public Result<?> submitData(@Param("..") TemplateCodeUpdateDTO dto) {
        houseHoldSurveyPdfService.submitData(dto);
        return Result.success();
    }

    @At("/v2/list")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取列表数据 2.0版本")
    @ApiResponses
    @SaCheckLogin
    public Result<?> list(@Param("pageNo") Integer pageNo, @Param("pageSize") Integer pageSize,
                          @Param("sort") String sort, @Param("fillDate") String fillDate,
                          @Param("id") String id, @Param("category") String category) {
        return houseHoldSurveyPdfService.list(pageNo, pageSize, fillDate, sort, id, category);
    }

    @At("/v2/update")
    @Ok("json")
    @POST
    @ApiOperation(name = "更新 2.0版本")
    @SaCheckLogin
    public Result<?> update(@Param("..") TemplateCodeUpdateDTO dto) {
        houseHoldSurveyPdfService.update(dto);
        return Result.success();
    }

    @At("/v2/latest")
    @Ok("json")
    @GET
    @ApiOperation(name = "获取人员最新一条巡查记录 2.0版本")
    @SaCheckLogin
    public Result<?> getLatest(@Param("personId") String personId) {
        return Result.data(houseHoldSurveyPdfService.getLatest(personId));
    }

    @At("/v2/checkData")
    @Ok("json")
    @POST
    @ApiOperation(name = "数据检测 2.0版本")
    @SaCheckLogin
    public Result<?> checkData(@Param("..") DownExcelLedgerReqVo reqVo) {

        List<DownFileTypesResVo> downFileTypesResVos = new ArrayList<>();

        reqVo.setCheckData(true);

        // pdf
        List<ResultOfExcelGenerator> generatePdfUrlVOList = houseHoldSurveyPdfService.downPdfList(reqVo);
        for (ResultOfExcelGenerator vo : generatePdfUrlVOList) {
            HouseHoldSurveyEnum pdf = HouseHoldSurveyEnum.getEnum(vo.getFileIdentity());
            DownFileTypesResVo resVo = new DownFileTypesResVo();
            resVo.setLabel(pdf.getName())
                    .setPreviewImage(List.of(pdf.getImg().split(",")))
                    .setFileCode(String.valueOf(pdf.getCode()))
                    .setCreatedAt(System.currentTimeMillis())
                    .setLocation(Integer.parseInt(pdf.getCode()))
                    .setFileName(pdf.getCompilationName())
                    .setFileType(pdf.getFileType())
                    .setHiveData(vo.getPassCreateConditionFlag() == null ? false : vo.getPassCreateConditionFlag());
            downFileTypesResVos.add(resVo);
        }

        // excel
        DownDataVo<ResultOfExcelGenerator> downDataVo = houseHoldSurveyExcelService.createExcel(reqVo);
        List<ResultOfExcelGenerator> generateExcelUrlVOList = downDataVo.getVoList();
        for (ResultOfExcelGenerator vo : generateExcelUrlVOList) {
            DownFileTypesResVo resVo = new DownFileTypesResVo();
            HouseHoldSurveyEnum excel = HouseHoldSurveyEnum.getEnum(vo.getFileIdentity());
            resVo.setLabel(excel.getName())
                    .setPreviewImage(List.of(excel.getImg().split(",")))
                    .setFileCode(String.valueOf(excel.getCode()))
                    .setCreatedAt(System.currentTimeMillis())
                    .setLocation(Integer.parseInt(excel.getCode()))
                    .setFileName(excel.getCompilationName())
                    .setFileType(excel.getFileType())
                    .setHiveData(vo.getPassCreateConditionFlag() == null ? false : vo.getPassCreateConditionFlag());
            downFileTypesResVos.add(resVo);
        }
        return Result.data(NutMap.NEW().addv("list", downFileTypesResVos).addv("totalCount", downDataVo.getTotalCount()));
    }

    @At("/v2/downPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "下载pdf 2.0版本")
    @SaCheckLogin
    public Result<?> downPdf(@Param("..") DownExcelLedgerReqVo reqVo) {
        List<ResultOfExcelGenerator> generatePdfUrlVOList = houseHoldSurveyPdfService.downPdfList(reqVo);
        return Result.data(generatePdfUrlVOList);
    }

    @At("/v2/downExcel")
    @Ok("json")
    @POST
    @ApiOperation(name = "下载excel 2.0版本")
    @SaCheckLogin
    public Result<?> downExcel(@Param("..") DownExcelLedgerReqVo reqVo) {
        DownDataVo<ResultOfExcelGenerator> downDataVo = houseHoldSurveyExcelService.createExcel(reqVo);
        return Result.data(downDataVo.getVoList());
    }

    @At()
    @Ok("json")
    @POST
    @ApiOperation(name = "新增人员信息")
    @SaCheckLogin
    public Result<?> addPersonInfo(@Param("..") PersonInfo personInfo) {
        return houseHoldSurveyPdfService.addPersonInfo(personInfo);
    }

    @At()
    @Ok("json")
    @POST
    @ApiOperation(name = "更新人员信息")
    @SaCheckLogin
    public Result<?> updatePersonInfo(@Param("..") PersonInfo personInfo) {
        return houseHoldSurveyPdfService.updatePersonInfo(personInfo);
    }

    @At()
    @Ok("json")
    @GET
    @ApiOperation(name = "获取人员信息")
    @SaCheckLogin
    public Result<?> getPersonInfo(@Param("id") String id) {
        return Result.data(personInfoService.fetch(id));
    }


    @At()
    @Ok("json")
    @POST
    @ApiOperation(name = "获取人员信息列表")
    @SaCheckLogin
    public Result<?> listPage(@Param("pageNo") Integer pageNo, @Param("pageSize") Integer pageSize,
                              @Param("query") String query, @Param("category") String category) {
        return Result.data(houseHoldSurveyPdfService.pagePersonInfo(pageNo, pageSize, query, category));
    }

    @At()
    @Ok("json")
    @GET
    @ApiOperation(name = "数据清洗")
    @SaCheckLogin
    public Result<?> dataCleanse() {
        dataCleanse(0);
        return Result.success();
    }

    private void dataCleanse(int page) {
        String sql = "select * from shequ.sqfw_form_summary where county  ='威清门街道' and type='入户调查' order by create_date asc LIMIT 100 OFFSET " + page;
        List<Sqfw_formSummary> formSummaryList = sqfwFormSummaryService.listEntity(Sqls.create(sql));
        for (Sqfw_formSummary formSummary : formSummaryList) {
            System.out.println("老数据："+ JSON.toJSONString(formSummary));
            try {
                if (StringUtils.isNotBlank(formSummary.getParamData())) {
                    // 添加人员
                    boolean isx = true;
                    String birth = null;
                    String sMark = null;
                    Sqfw_cenSusPaper paper = JSONUtil.toList(formSummary.getParamData(), Sqfw_cenSusPaper.class).get(0);
                    PersonInfo personInfo;
                    if (StringUtils.isBlank(paper.getCardId())) {
                        Cnd cnd = Cnd.NEW();
                        cnd.and(PersonInfo::getName, "=", paper.getName());
                        cnd.and(PersonInfo::getCommunity, "=", formSummary.getCommunity());
                        personInfo = personInfoService.fetch(cnd);

                        if (personInfo == null) {
                            personInfo = new PersonInfo();
                            isx = false;
                        }
                    } else {
                        Cnd cnd = Cnd.NEW();
                        cnd.and(PersonInfo::getIdNumber, "=", paper.getCardId());
                        cnd.and(PersonInfo::getCounty, "=", formSummary.getCounty());
                        cnd.and(PersonInfo::getCommunity, "=", formSummary.getCommunity());
                        personInfo = personInfoService.fetch(cnd);
                        if (personInfo == null) {
                            personInfo = new PersonInfo();
                            isx = false;
                        }
                        //生日
                        birth = IdcardUtil.getBirthByIdCard(paper.getCardId());
                        personInfo.setBirthDate(DateUtil.toLocalDateTime(DateUtil.parse(birth, DatePattern.NORM_DATE_PATTERN)).toLocalDate());
                    }

                    personInfo.setName(paper.getName());
                    personInfo.setPhone(paper.getPhone());
                    personInfo.setIdNumber(paper.getCardId());

                    personInfo.setUnitName(formSummary.getUnitName());
                    personInfo.setProvince(formSummary.getProvince());
                    personInfo.setCity(formSummary.getCity());
                    personInfo.setDistrict(formSummary.getDistrict());
                    personInfo.setCounty(formSummary.getCounty());
                    personInfo.setCommunity(formSummary.getCommunity());
                    personInfo.setCreateBy(formSummary.getCreateBy());
                    personInfo.setUpdateBy(formSummary.getUpdateBy());
                    personInfo.setCreateDate(LocalDateTime.now());
                    if (personInfo.getBirthDate() != null) {
                        personInfo.setAge(DateUtil.ageOfNow(new DateTime(personInfo.getBirthDate())));
                    }

                    sMark = paper.getSpecialMark();
                    List<PeopleTagDTO> specialMark = new ArrayList<>();
                    if (StringUtils.isNotBlank(sMark)) {
                        List<String> careCategory = Arrays.asList(sMark.split(","));
                        PeopleTagDTO tagDTO = new PeopleTagDTO();
                        tagDTO.setBusinessType(houseHoldSurveyPdfService.getSummaryType());
                        List<PeopleTagDTO.Dict> tag = new ArrayList<>();
                        for (String v : careCategory) {
                            if ("单独居老人".equals(v) || "双独居老人".equals(v)) {
                                v = "老";
                            }
                            if ("无".equals(v) || "正常".equals(v)) {
                                v = "正常";
                            }
                            PeopleTagDTO.Dict dict = new PeopleTagDTO.Dict();
                            dict.setBusinessType("走访人员类别");
                            dict.setName(v);
                            tag.add(dict);
                        }
                        tagDTO.setTag(tag);
                        specialMark.add(tagDTO);
                    }
                    personInfo.setSpecialMark(JSONUtil.toList(JSONUtil.toJsonStr(specialMark), PersonnelTagDTO.class));
                    String address = null;
                    if (StringUtils.isNotBlank(formSummary.getA1())) {
                        address = formSummary.getA1();
                        if (StringUtils.isNotBlank(formSummary.getA4())) {
                            address += formSummary.getA4();
                        }
                        if (StringUtils.isNotBlank(formSummary.getA5())) {
                            address += formSummary.getA5();
                        }
                    }
                    personInfo.setAddress(address);
                    personInfo.setBusinessType(houseHoldSurveyPdfService.getSummaryType());

                    if (isx) {
                        personInfoService.updateIgnoreNull(personInfo);
                    } else {
                        personInfo = personInfoService.insert(personInfo);
                    }

                    // 添加巡查
                    TemplateCodeUpdateDTO dto = new TemplateCodeUpdateDTO();
                    HouseHoldSurveyDTO holdSurveyDTO = new HouseHoldSurveyDTO();
                    holdSurveyDTO.setId(personInfo.getId());
                    holdSurveyDTO.setName(personInfo.getName());
                    holdSurveyDTO.setIDNumber(personInfo.getIdNumber());
                    holdSurveyDTO.setBirthday(birth == null ? null : DateUtil.parse(birth, DatePattern.NORM_DATE_PATTERN));
                    holdSurveyDTO.setPhone(personInfo.getPhone());
                    holdSurveyDTO.setAddress(personInfo.getAddress());
                    List<String> list = new ArrayList<>();
                    if (StringUtils.isNotBlank(sMark)) {
                        for (String v : sMark.split(",")) {
                            if ("单独居老人".equals(v) || "双独居老人".equals(v)) {
                                v = "老";
                            }
                            if ("无".equals(v) || "正常".equals(v)) {
                                v = "正常";
                            }
                            list.add(v);
                        }
                    }
                    holdSurveyDTO.setCareCategory(list);

                    List<InterviewDTO> interviewDTOList = new ArrayList<>();
                    InterviewDTO interviewDTO = new InterviewDTO();
                    interviewDTO.setFillDate(formSummary.getFillDate());
                    String url = null;
                    if (StringUtils.isNotBlank(formSummary.getA11())) {
                        url = formSummary.getA11();
                    }
                    if (StringUtils.isNotBlank(formSummary.getA11())) {
                        if (url == null) {
                            url = formSummary.getA12();
                        } else {
                            url += "," + formSummary.getA11();
                        }
                    }
                    interviewDTO.setVisitPictures(url);
                    interviewDTOList.add(interviewDTO);
                    holdSurveyDTO.setInterviewDTOList(interviewDTOList);

                    Sqfw_formSummary_new formSummaryNew = new Sqfw_formSummary_new();
                    BeanUtil.copyProperties(formSummary, formSummaryNew);
                    formSummaryNew.setParamData(JSONUtil.toJsonStr(holdSurveyDTO));
                    dto.setFormSummary(formSummaryNew);

                    Sqfw_formSummary_new f = sqfwFormsummaryNewService.fetch(formSummary.getId());
                    if (f == null) {
                        sqfwFormsummaryNewService.insert(formSummaryNew);
                    } else {
                        sqfwFormsummaryNewService.update(formSummaryNew);
                    }
                    houseHoldSurveyPdfService.reCreatePdfAndMsg(formSummaryNew.getSqfwFlowId());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (formSummaryList.size() == 100) {
            page += 100;
            dataCleanse(page);
        }
    }
}
